﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using MyCloudHelpers;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Xml.Linq;

namespace LocalTweetWebRole.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string strUserAgent = Request.UserAgent.ToString().ToLower();
            if (strUserAgent != null)
            {
                if (Request.Browser.IsMobileDevice == true || strUserAgent.Contains("iphone") || 
                    strUserAgent.Contains("blackberry") || strUserAgent.Contains("mobile") || 
                    strUserAgent.Contains("windows ce") || strUserAgent.Contains("opera mini") || 
                    strUserAgent.Contains("palm"))
              {
                  
              }
                else
                {
                    ViewData["Message"] = @"<script type='text/javascript'><!--
google_ad_client = 'pub-1636062416876828';
/* 468x60, date de création 09/03/10 */
google_ad_slot = '9038039822';
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type='text/javascript'
src='http://pagead2.googlesyndication.com/pagead/show_ads.js'>
</script>";
                }
            }


            
           // ViewData["Message"] = "Welcome to ASP.NET MVC!";
            ViewData.Model = null;
            /*var TweetsQueue =QueueHelper.queueStorage.GetQueueReference("TweetsToSearch");
            TweetsQueue.AddMessage(new CloudQueueMessage("this.ControllerContext.HttpContext.Request.UserLanguages"));
            */

            return View();
        }
        //[ChildActionOnly]
        //public ActionResult Menu()
        //{
        //    var menu = GetMenuFromSomewhere();
        //    return PartialView(menu);
        //}
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TwittListNext(string next)
        {
            XmlReader reader = XmlReader.Create(next);
            SyndicationFeed feed = SyndicationFeed.Load(reader);
            if(feed.Links.Where(link => link.RelationshipType == "next").Count()>0)
                ViewData["Next"] = "<a href='#' id='more' onclick='javascript:NextList(\"" + Url.Encode(feed.Links.Where(link => link.RelationshipType == "next").First().Uri.ToString()) + "\")'>+ de résultats ...</a>";
            
            return PartialView("TwittList", feed.Items.ToList());
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TwittList(string SearchText, string latit, string longit, string distance, string nb)
        {
            //string nb="2";
            string lang="";
          
            if (this.ControllerContext.HttpContext.Request.UserLanguages != null)
            {
                lang = this.ControllerContext.HttpContext.Request.UserLanguages.First().ToString().Substring(0, 2);
            }
            else
            {
                lang = "fr";
            }
            string apicall;   
           
            apicall = "http://search.twitter.com/search.atom?rpp=";
            if (nb != null && int.Parse(nb) < 11 && int.Parse(nb) > 0)
                apicall += nb;
            //apicall += "&lang=" + lang;
            if (!String.IsNullOrEmpty(SearchText))
            {
                apicall += "&q=" + SearchText;
            }
            Boolean geoloc=false;
            if (latit != null && longit != null && latit != "" && longit != "")
            {
                
                geoloc = true;
            }
            else // on tente une géolocalisation par IP 
            {
                string IpGeolocCall;
                IpGeolocCall = "http://ipinfodb.com/ip_query.php" + "?ip=" + Request.UserHostAddress + "&timezone=false";
                try
                {
                    using (XmlReader readerIp = XmlReader.Create(IpGeolocCall))
                    {
                        XDocument xdoc = XDocument.Load(readerIp);
                        latit = xdoc.Descendants("Latitude").First().Value;
                        longit = xdoc.Descendants("Longitude").First().Value;
                        geoloc = true;
                    }
                }
                catch (Exception)
                {
                    geoloc = false;
                }
                
            }
            
            if (geoloc)//si pas de latitude et de longitude et de texte spécifié on met la publictimeline
            {
                apicall += "&geocode=" + latit + "%2C" + longit;
                if (distance != null && int.Parse(distance) > 0 && int.Parse(distance) < 21)
                    apicall += "%2C" + distance + "km";
            }
            else
            {
                apicall = "http://api.twitter.com/1/statuses/public_timeline.atom";
            }

            XmlReader reader = XmlReader.Create(apicall);
            SyndicationFeed feed = SyndicationFeed.Load(reader);
            ViewData["Message"] = "Autour de moi dans un rayon de " + distance + "km les derniers twitts sont :<br /><br/>";
            if (feed.Links.Where(link => link.RelationshipType == "next").Count() > 0)
                ViewData["Next"] = "<a href='#' id='more' onclick='javascript:NextList(\"" + Url.Encode(feed.Links.Where(link => link.RelationshipType == "next").First().Uri.ToString()) + "\")'>+ de résultats ...</a>";

             return PartialView("TwittList", feed.Items.ToList());
        } 

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult Index(string SearchText,string longit,string latit ,string distance)
        //{
        //    XmlReader reader = XmlReader.Create("http://search.twitter.com/search.atom?rpp=10&q=" + SearchText + "&geocode=" + latit + "%2C" + longit + "%2C"+ distance +"km" + "&lang=" + this.ControllerContext.HttpContext.Request.UserLanguages.First().ToString().Substring(0,2));
        //    SyndicationFeed feed = SyndicationFeed.Load(reader);
        //    ViewData.Model = feed.Items.ToList();
        //    //feed.Items.ToList()[0] 
        //    ViewData["Message"] = distance;
        //    //ViewData["Message"] = "http://search.twitter.com/search.atom?rpp=10&q=" + SearchText + "&geocode=" + latit + "%2C" + longit + "%2C" + "23km" + "&lang=" + this.ControllerContext.HttpContext.Request.UserLanguages.First().ToString().Substring(0,2);
        //    return View("result");
        //}

        public ActionResult About()
        {
            return View();
        }
    }
}
